<?php

class MembersReportController extends Controller
{
	public function actionIndex()
	{
		if(isset($_POST["GetReport"]))
		{
			$sql = "SELECT  `member_id`, 
							`first_name`,
							`last_name`,
							`email`,
							`mobile_no`,
							`main_address`,
							`secondary_address`,
							`postal_code` 
					FROM  `gn_members` 
					where YEAR(date_created) = ". $_POST["year"] ." and MONTH(date_created) = " . $_POST["month"];
			$this->forImportFormat($sql);
	    }
		else
			$this->render('index');
	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/

	public function actionExcelMemberReport()
	{
		$sql = "SELECT  `member_id`, 
						`first_name`,
						`last_name`,
						`email`,
						`mobile_no`,
						`main_address`,
						`secondary_address`,
						`postal_code` 
				FROM  `gn_members`";
		$this->forImportFormat($sql);
	}

	function forImportFormat($sql)
	{
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql);
		    $result = $command->query()->readAll();   

			$filename = "member_list_".date("mdy").".csv";
			header('HTTP/1.1 200 OK');
	        header("Content-type: application/octet-stream");
	        header("Content-Disposition: attachment; filename=\"$filename\"");

	        $header = "First Name, Last Name, E-Mail, Phone Number, Address 1, Address 2, City, State, Zip, Country, Comments, Account Number, Taxable, Company Name,GnMember ID\n";
	        echo $header;

	        if(count($result)>0)
	        {
	        	foreach ($result as $node) {
	        		$member = array();
	        		$member["FirstName"] = $node["first_name"];
	        		$member["LastName"] = $node["last_name"];
	        		$member["email"] = $node["email"];
	        		$member["PhoneNumber"] = $node["mobile_no"];
	        		$member["Address1"] = $node["main_address"];
	        		$member["Address2"] = $node["secondary_address"];
	        		$member["City"] = "";
	        		$member["State"] = "";
	        		$member["Zip"] = $node["postal_code"];
					$member["Country"] = "";
	        		$member["Comments"] = "";
	        		$member["AccountNumber"] = "";
	        		$member["Taxable"] = "";
	        		$member["CompanyName"] = "";
					$member["GnMemberId"] = $node["member_id"];

	        		$members = implode(",", $member);
	        		echo "$members\n";

	        	}
	        }
	}
}